# -*- coding: utf-8 -*-
"""
Created on Tue Mar 14 16:04:42 2023

@author: Derek Rodriguez Pacheco, PhD
IUSS Pavia
"""

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

testnumber= [13,14,15,16,17,18,19,20,24,25,26,27,28,40,41]

data= {}
accelt01= {}
accelt02= {}
accelcm= {}
time= {}

datav= {}
acceltv= {}
timev= {}
time0= []
timef= []

for i in range(15):
    data['%d' % (i+1)]= np.array(pd.read_csv('%d_AccelAndDispl_15Hz.txt' % testnumber[i], header= None, delim_whitespace= True))
    datav['%d' % (i+1)]= np.array(pd.read_csv('Comparison_Acceleration\\%d_time_baseAcc_displGross_displNet_topAcc_filterLP_15Hz.txt' % testnumber[i], header= None, delim_whitespace= True))
    accelt01['%d' % (i+1)]= np.array(data['%d' % (i+1)][:,2])
    accelt02['%d' % (i+1)]= np.array(data['%d' % (i+1)][:,3])
    accelcm['%d' % (i+1)]= np.array(data['%d' % (i+1)][:,4])
    acceltv['%d' % (i+1)]= np.array(datav['%d' % (i+1)][:,4])
    time['%d' % (i+1)]= np.array(data['%d' % (i+1)][:,0])
    timev['%d' % (i+1)]= np.array(datav['%d' % (i+1)][:,0])
    time0.append(datav['%d' % (i+1)][0,0])
    timef.append(datav['%d' % (i+1)][-1,0])


nr= 3
nc= 5

intensity= [0.17,0.17,0.19,0.20,0.20,0.19,0.20,0.40,0.29,0.29,0.34,0.39,0.46,0.51,0.52]
location1= [1800,2700,2700,2700,2700,2700,2700,2700,2700,2700,2700,2700,2700,2700,2700]
location2= [4000,11000,11000,11000,11000,11000,11000,11000,11000,11000,11000,11000,11000,11000,11000]
location3= [-58,-58,-58,-58,-58,-58,-58,-58,-58,-58,-58,-58,-58,-58,-58]

def maxim(signala, signalt, limit):
    amp= []
    tim= []
    indexes= []
    for index,i in enumerate(signala):
        if abs(i)>limit and abs(i)>abs(signala[index-1]) and abs(i)>abs(signala[index+1]):
            amp.append(i)
            tim.append(signalt[index])
            indexes.append(index)
    return amp, tim, indexes

def begin(signalt, bgt):
    for index,i in enumerate(signalt):
        if i==bgt:
            beginindex= index
    return beginindex
        

maximacm= []
maximtcm= []
maximicm= []
maximav= []
maximtv= []
maximiv= []
# correspv= []
bindexes= []
findexes= []
# correctindex= []
averagecm= []
averagev= []


for i in range(15):
    if i<=6:
        limit= 2
    else:
        limit= 3
    testa, testt, testindex= maxim(accelcm['%d' % (i+1)], time['%d' % (i+1)], limit)
    testa2, testt2, testindex2= maxim(acceltv['%d' % (i+1)], timev['%d' % (i+1)], limit)
    bindexes.append(begin(time['%d' % (i+1)], time0[i]))
    findexes.append(begin(time['%d' % (i+1)], timef[i]))
    # testav, testtv= maxim(acceltv['%d' % (i+1)], timev['%d' % (i+1)])
    maximacm.append(testa)
    maximtcm.append(testt)
    maximicm.append(testindex)
    maximav.append(testa2)
    maximtv.append(testt2)
    maximiv.append(testindex2)
    # correctindex.append(np.array(maximicm[i])-bindexes[i])
    # correspv.append([acceltv['%d' % (i+1)][j] for j in correctindex[i]])
    # ratiosa.append(np.array(maximacm[i])/np.array(correspv[i]))
    averagecm.append(np.average(abs(np.array(maximacm[i]))))
    averagev.append(np.average(abs(np.array(maximav[i]))))

ratiosdcm= np.array(averagecm)/np.array(averagev)

np.savetxt('Adjustment_Factors_Displacement_CM1.txt', ratiosdcm)

# ratiosa= np.array([maximacm[i]])



fig3, ax3 = plt.subplots(nr,nc, figsize= (13,8))

            
for i in range(nr):
    for j in range(nc):
        count= nc*i+(j+1)
        ax3[i,j].plot(timev['%d' % count], acceltv['%d' % count], alpha= 1, color= 'limegreen', lw= 1.5, label= 'Top specimen')
        ax3[i,j].plot(time['%d' % count], accelcm['%d' % count], alpha= 0.75, color= '#FF8787', lw= 1.5, label= 'Center of mass')
                
        if count==11 or count==12 or count==13 or count==14 or count==15:
            ax3[i,j].set_xlabel('Time (s)')
        if count==1 or count==6 or count==11:
            ax3[i,j].set_ylabel('Acceleration (g)')
        ax3[i,j].annotate('Test Number: %d\nPTA= %.2fg' % (testnumber[count-1],intensity[count-1]),
                      xy = (1, location3[count-1]), 
                      xycoords = 'data',
                      xytext = (+0, +0), 
                      textcoords = 'offset points', 
                      fontsize = 9,
                      # weight= 'bold',
                      color = 'black',
                      )
        ax3[i,j].set_xticks([0,20,40,60])
        # ax3[i,j].set_yticks([-60,-40,-20,0,20,40,60])
        ax3[i,j].set_xlim([0,60])
        # ax3[i,j].set_ylim([-60,60])
        # if count!=1 and count!=6 and count!=11:
            # ax3[i,j].set_yticklabels([])
        # if count!=11 and count!=12 and count!=13 and count!=14 and count!=15:
        #     ax3[i,j].set_xticklabels([])
        ax3[i,j].set_facecolor('#DEE2E6')
        ax3[i,j].grid(color= 'black', ls= '--', lw= 0.5)
        if count==1:
            ax3[i,j].legend()
        
        
fig3.tight_layout()    
# fig3.savefig('Relative_Displacement.svg', bbox_inches= 'tight')    

    
    
    
    
    